//车辆轨迹定位

interface ICarStrackViewModel extends ng.IScope{
    // Test_ak:string;
    // ServiceId:string;
    /**
     * 车辆编号
     */
    carId:string;
    isVehicle:boolean;
    shipTime:string;
    realArrivalTime:string;
    carcode:string;
    phone:string;
    shipAddress:string;
    deliverAddress:string;
    
    presentTime:number;
    statusCode:string;
    area:string;

    creationTime:string;
    /**
     * 返回事件
     */
    goback:()=>void;
}

class ICarStrack{
    adds=[];
    myGeo=null;
    geoc=null;
    Test_ak:string;
    ServiceId:string;
    ab=[];
    cc=[];
    j:number = 0;
    k:number = 0;
    timer:any;//10秒更新一次
    startTime:number;


    constructor(private $scope:ICarStrackViewModel,private locationService:locationService,private orderService:IorderService,
    private trackService:IStrackService,private $location: ng.ILocationService,private $ngBootbox: BootboxService,
    private $timeout:ng.ITimeoutService,private routeService:routeService,private $state: angular.ui.IStateService){
        this.init();
    }

    init():void{
        this.Test_ak = "tM6LA0Ub35kT4mt5rtwph37BPVQOcAvZ";
        this.ServiceId = "122030";

        //定位API接口必须要参数
        this.$scope.isVehicle = true;
        this.$scope.carId = this.$location.search().id;

        //添加好unix时间戳
        this.$scope.shipTime = this.$location.search().shipTime;  
        if(this.$location.search().shipTime){
            this.startTime = this.unixtime(this.$location.search().shipTime);
        }

        this.$scope.realArrivalTime = this.$location.search().realArrivalTime;
        if(this.$scope.realArrivalTime){
            this.unixtime(this.$scope.realArrivalTime);
        }

        this.$scope.carcode = this.$location.search().carcode;
        this.$scope.phone = this.$location.search().phone;
        this.$scope.shipAddress = this.$location.search().shipAddress;
        this.$scope.deliverAddress = this.$location.search().deliverAddress;
        //地址
        this.adds=[this.$location.search().shipAddress,this.$location.search().deliverAddress];

        this.$scope.presentTime = Math.round(new Date().getTime()/1000);

        this.$scope.statusCode="";
        this.$scope.area = "--";

        //逆地址解析初始化
        this.myGeo = new BMap.Geocoder();
        this.geoc = new BMap.Geocoder();

        this.initMap();
        this.judgealltime();
        this.s_eStart();

        this.$scope.$on('$destroy', ()=>{//清除timeout
            this.$timeout.cancel(this.timer);
        });

        this.$scope.goback = this.goback;

    }

    //创建和初始化地图函数：
    initMap=()=> {
        this.createMap(); //创建地图
        this.setMapEvent(); //设置地图事件       
    }

    //创建地图函数：
    createMap=()=> {
        var map = new BMap.Map("dituContent"); //在百度地图容器中创建一个地图       
        (<any>window).map = map; //将map变量存储在全局
    }

    //地图事件设置函数：
    setMapEvent=()=> {
        (<any>window).map.enableScrollWheelZoom(); //启用地图滚轮放大缩小
    }

     // 编写创建标注函数
    addMarker=(point, label)=> {
        var markers = [{
            imageOffset: {
                width: -69, height: -21
            }
        }];
        var myIcon = new BMap.Icon("https://api.map.baidu.com/lbsapi/createmap/images/icon.png", new BMap.Size(20, 25), {
            imageOffset: new BMap.Size(markers[0].imageOffset.width, markers[0].imageOffset.height)
        });
        var marker = new BMap.Marker(point, {
            icon: myIcon
        });
        (<any>window).map.addOverlay(marker);
        marker.setLabel(label);
    }

    addMarker2=(point, label)=> {
        var markers = [{
            imageOffset: {
                width: 0, height: -21
            }
        }];
        var myIcon = new BMap.Icon("https://api.map.baidu.com/lbsapi/createmap/images/icon.png", new BMap.Size(20, 25), {
            imageOffset: new BMap.Size(markers[0].imageOffset.width, markers[0].imageOffset.height)
        });
        var marker2 = new BMap.Marker(point, {
            icon: myIcon
        });
        (<any>window).map.addOverlay(marker2);
        marker2.setLabel(label);
    }

    //逆地址解析函数,发货地址使用
    s_eStart=()=>{
        this.myGeo.getPoint(this.adds[0],(point)=>{
            if (point) {
                var address = new BMap.Point(point.lng, point.lat);
                this.addMarker2(address, new BMap.Label(this.adds[0], {
                    offset: new BMap.Size(20, -10)
                }));
                this.s_eEnd();
            }
        });
    }

    //逆地址解析函数,送货地址使用
    s_eEnd=()=> {
        this.myGeo.getPoint(this.adds[1],(point)=>{
            if (point) {
                var address = new BMap.Point(point.lng, point.lat);
                this.addMarker2(address, new BMap.Label(this.adds[1], {
                    offset: new BMap.Size(20, -10)
                }));
            }
        });
    }

    //常用显示时间转化成unix时间戳
    unixtime=(stringtime)=> {
        var str = stringtime.replace(/-/g, "/");
        var date = new Date(str);
        var humanDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
        return (humanDate.getTime() / 1000 - 8 * 60 * 60);
    }

    //unix时间戳转化为常用时间
    normaltime=(timer)=> {
        return new Date(timer * 1000).toLocaleString();
    }

    //封装显示定位成功功能函数
    ShowLocationTime=(x)=> {
        var pt = new BMap.Point(x.location[0], x.location[1]);
        this.geoc.getLocation(pt,  (res)=> {
            var addComp = res.addressComponents;
            this.$scope.area = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
            this.$scope.statusCode = "成功";
        })
        this.$scope.creationTime = this.normaltime(x.loc_time);
        (<any>window).map.centerAndZoom(pt, 20);
    }

    //添加每一天的随机点
    Random_poi(data) {
        var random_poi = data.points[Math.floor(Math.random() * data.points.length)]
        this.addMarker2(new BMap.Point(random_poi.location[0], random_poi.location[1]), new BMap.Label("定位时间" + this.normaltime(random_poi.loc_time), {
            offset: new BMap.Size(20, -10)
        }));
    }

    //历史轨迹定位(以天数划分)
    start_end_all_points=(shipTime, realArrivalTime)=> {
        var point_array = [];
        var polyline;
        var his_pois;
        if ((shipTime + 86400) < realArrivalTime) {
            this.trackService.jsonp(this.routeService.getHistoryUrl(this.routeService.Entity.History,{
                ak: this.Test_ak,
                service_id: this.ServiceId,
                start_time: shipTime,
                end_time: shipTime+86399,
                entity_name: this.$scope.phone,
                sort_type: 1,
                simple_return: 0,
                is_processed: 1,
                process_option: "",
                supplement_mode: "",
                page_index: 1,
                page_size: 2880
            }),"","","","","").then( (data)=>{
                if (data.status !== 0) {
                    console.log(data.status);
                    if(!data.message){
                            this.$ngBootbox.alert(data.message).then(()=> {
                                this.goback();
                            },()=>{ return });
                    }else{
                        this.$ngBootbox.alert("该司机的手机号没有绑定来货拉，无法定位，点击关闭自动退出").then(()=> {
                            this.goback();
                        },()=>{ return });
                    }
                    //return;
                } else if (data.total == 0) {
                    shipTime = shipTime + 86400;
                    this.start_end_all_points(shipTime, realArrivalTime);
                } else {
                    this.j++;
                    for (var i = 0; i < data.points.length; i++) {
                        point_array.push(new BMap.Point(data.points[i].location[0], data.points[i].location[1]))
                    }
                    this.Random_poi(data);
                    this.cc[this.j] = data.points[0];
                    his_pois = data.points[data.points.length - 1];
                    this.ab.push(his_pois);
                    (<any>window).map.centerAndZoom(new BMap.Point(his_pois.location[0], his_pois.location[1]), 100);
                    polyline = new BMap.Polyline(point_array, { strokeColor: "#23b7e5", strokeWeight: 3, strokeOpacity: 0.8 }); //创建折线
                    (<any>window).map.addOverlay(polyline); //增加折线
                    shipTime = shipTime + 86400;
                    this.start_end_all_points(shipTime, realArrivalTime);
                }
            });
        } else {
            this.trackService.jsonp(
                this.routeService.getHistoryUrl(this.routeService.Entity.History,{
                ak: this.Test_ak,
                service_id: this.ServiceId,
                start_time: shipTime,
                end_time: this.$scope.realArrivalTime,
                entity_name: this.$scope.phone,
                sort_type: 1,
                simple_return: 0,
                is_processed: 1,
                process_option: "",
                supplement_mode: "",
                page_index: 1,
                page_size: 2880
            }),"","","","","").then( (data) =>{
                if (data.status !== 0) {
                    this.$ngBootbox.alert("该司机的手机号没有绑定来货拉，无法定位，弹窗关闭自动退出").then(()=> {
                        this.goback();

                        return;
                    })
                } else if (data.total == 0) {
                    if (this.ab.length == 0 || this.cc.length == 0) {
                        this.$ngBootbox.alert("从发货到送货结束这段时间,司机没开起来货拉的定位服务,弹窗关闭后退出").then(()=> {
                            this.goback();

                            return;
                        })
                    } else {
                        his_pois = this.ab[this.ab.length - 1];
                        this.addMarker2(new BMap.Point(this.cc[1].location[0], this.cc[1].location[1]), new BMap.Label("起点", {
                            offset: new BMap.Size(25, -10)
                        }));
                        this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("最新定位" + this.normaltime(his_pois.loc_time), {
                            offset: new BMap.Size(20, -10)
                        }));
                        this.ShowLocationTime(his_pois)
                    }
                } else {
                    for (var i = 0; i < data.points.length; i++) {
                        point_array.push(new BMap.Point(data.points[i].location[0], data.points[i].location[1]))
                    }
                    his_pois = data.points[data.points.length - 1];
                    this.Random_poi(data);
                    if (this.j !== 0) {
                        console.log("起点已经有了");
                    } else {
                        this.j++;
                        this.cc[this.j] = data.points[0];
                    }
                    this.ShowLocationTime(his_pois);
                    this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("终点" + this.normaltime(his_pois.loc_time), {
                        offset: new BMap.Size(25, -10)
                    }));
                    this.addMarker2(new BMap.Point(this.cc[1].location[0], this.cc[1].location[1]), new BMap.Label("起点", {
                        offset: new BMap.Size(20, -10)
                    }));
                    (<any>window).map.addOverlay(new BMap.Polyline(point_array, { strokeColor: "#23b7e5", strokeWeight: 3, strokeOpacity: 0.8 })); //增加折线
                }
            });
        }
    }



    start_end_all_points2=(shipTime, presentTime)=> {
            var point_array = [];
            var polyline;
            var his_pois;
            if ((shipTime + 86400) < presentTime) {
                this.trackService.jsonp(this.routeService.getHistoryUrl(this.routeService.Entity.History,{
                    ak: this.Test_ak,
                    service_id: this.ServiceId,
                    start_time: shipTime,
                    end_time: shipTime + 86399,
                    entity_name: this.$scope.phone,
                    sort_type: 1,
                    simple_return: 0,
                    is_processed: 1,
                    process_option: "",
                    supplement_mode: "",
                    page_index: 1,
                    page_size: 2880
                }),"","","","","").then( (data)=> {
                    if (data.status !== 0) {
                        this.$ngBootbox.alert("该司机的手机号没有绑定来货拉，无法定位，弹窗关闭自动退出").then( (res)=> {
                            this.goback();

                            return;
                        },  (rel)=>{
                            return
                        });
                    } else if (data.total == 0) {
                        shipTime = shipTime + 86400;
                        this.start_end_all_points2(shipTime, presentTime);
                    } else {
                        for (var i = 0; i < data.points.length; i++) {
                            point_array.push(new BMap.Point(data.points[i].location[0], data.points[i].location[1]))
                        }
                        this.Random_poi(data);
                        this.j++;
                        this.cc[this.j] = data.points[0];
                        his_pois = data.points[data.points.length - 1];
                        this.ab.push(his_pois);
                        (<any>window).map.centerAndZoom(new BMap.Point(his_pois.location[0], his_pois.location[1]), 100);
                        polyline = new BMap.Polyline(point_array, { strokeColor: "#23b7e5", strokeWeight: 3, strokeOpacity: 0.8 }); //创建折线
                        (<any>window).map.addOverlay(polyline); //增加折线
                        shipTime = shipTime + 86400;
                        this.start_end_all_points2(shipTime, presentTime);
                    }
                });
            } else {
                this.trackService.jsonp(this.routeService.getHistoryUrl(this.routeService.Entity.History,{
                    ak: this.Test_ak,
                    service_id: this.ServiceId,
                    start_time: shipTime,
                    end_time: presentTime,
                    entity_name: this.$scope.phone,
                    sort_type: 1,
                    simple_return: 0,
                    is_processed: 1,
                    process_option: "",
                    supplement_mode: "",
                    page_index: 1,
                    page_size: 2880
                }),"","","","","").then( (data)=> {
                    if (data.status !== 0) {
                        this.$ngBootbox.alert("该司机的手机号没有绑定来货拉，无法定位，弹窗关闭自动退出").then( (res)=> {
                            this.goback();

                            return;
                        },  (rel)=> { return });
                    } else if (data.total == 0) {
                        if (this.ab.length == 0 || this.cc.length == 0) {
                            
                            his_pois = "";
                            this.drawJIT(his_pois);
                        } else {
                            his_pois = this.ab[this.ab.length - 1];
                            this.addMarker2(new BMap.Point(this.cc[1].location[0], this.cc[1].location[1]), new BMap.Label("起点", {
                                offset: new BMap.Size(25, -10)
                            }));
                            this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("最新定位" + this.normaltime(his_pois.loc_time), {
                                offset: new BMap.Size(20, -10)
                            }));
                            this.ShowLocationTime(his_pois)
                            this.drawJIT(his_pois)
                        }
                    } else {
                        for (var i = 0; i < data.points.length; i++) {
                            point_array.push(new BMap.Point(data.points[i].location[0], data.points[i].location[1]))
                        }
                        this.Random_poi(data);
                        his_pois = data.points[data.points.length - 1];
                        if (this.j !== 0) {
                        } else {
                            this.j++;
                            this.cc[this.j] = data.points[0];
                        }
                        this.ShowLocationTime(his_pois)
                        this.addMarker2(new BMap.Point(this.cc[1].location[0], this.cc[1].location[1]), new BMap.Label("起点", {
                            offset: new BMap.Size(20, -10)
                        }));
                        this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("最新定位" + this.normaltime(his_pois.loc_time), {
                            offset: new BMap.Size(20, -10)
                        }));
                        (<any>window).map.addOverlay(new BMap.Polyline(point_array, { strokeColor: "#23b7e5", strokeWeight: 3, strokeOpacity: 0.8 })); //增加折线
                        this.drawJIT(his_pois)
                    }
                });
            }
        }

        drawJIT=(his_pois)=> {
            var point_array = [];
            if (his_pois == "" || his_pois == undefined || his_pois == null) {
                this.trackService.jsonp(this.routeService.getEntityUrl(this.routeService.Entity.List,{
                    ak: this.Test_ak,
                    service_id: this.ServiceId,
                    entity_names: this.$scope.phone,
                    active_time: "",
                    return_type: "",
                    page_index: "",
                    page_size: ""
                }),"","","","","").then( (data)=>{
                    if (data && data.status === 0) {
                        var entidata = data.entities[0];
                        his_pois = {};
                            his_pois.location = entidata.realtime_point.location;
                            his_pois.loc_time = entidata.realtime_point.loc_time;
                            point_array.push(new BMap.Point(his_pois.location[0], his_pois.location[1]));
                            (<any>window).map.centerAndZoom(new BMap.Point(his_pois.location[0], his_pois.location[1]), 20);
                            this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("最新定位" + this.normaltime(his_pois.loc_time), {
                                offset: new BMap.Size(20, -10)
                            }));
                            (<any>window).map.addOverlay(new BMap.Polyline(point_array), {
                                strokeColor: "#ce1212", strokeWeight: 3, strokeOpacity: 0.8
                            }); //增加折线
                        
                        this.timer = this.$timeout(()=> {
                            this.drawJIT(his_pois);
                        }, 10000);
                    } else {
                        this.$ngBootbox.alert("数据库无法给出轨迹点，弹窗关闭退出").then( ()=> {
                            this.goback();
                            return;
                        })
                    }
                });
            } else {
                point_array.push(new BMap.Point(his_pois.location[0], his_pois.location[1]));
                this.trackService.jsonp(this.routeService.getEntityUrl(this.routeService.Entity.List,{
                    ak: this.Test_ak,
                    service_id: this.ServiceId,
                    entity_names: this.$scope.phone,
                    active_time: "",
                    return_type: "",
                    page_index: "",
                    page_size: ""
                }),"","","","","").then((data)=> {
                    if (data && data.status === 0) {
                        var entidata = data.entities[0];
                        if (his_pois.loc_time === entidata.realtime_point.loc_time) {
                        } else {
                            his_pois.location = entidata.realtime_point.location;
                            his_pois.loc_time = entidata.realtime_point.loc_time;
                            point_array.push(new BMap.Point(his_pois.location[0], his_pois.location[1]));
                            (<any>window).map.centerAndZoom(new BMap.Point(his_pois.location[0], his_pois.location[1]), 20);
                            this.addMarker(new BMap.Point(his_pois.location[0], his_pois.location[1]), new BMap.Label("最新定位" + this.normaltime(his_pois.loc_time), {
                                offset: new BMap.Size(20, -10)
                            }));
                            (<any>window).map.addOverlay(new BMap.Polyline(point_array), {
                                strokeColor: "#ce1212", strokeWeight: 3, strokeOpacity: 0.8
                            }); //增加折线
                        }
                        this.timer = this.$timeout(()=>{
                            this.drawJIT(his_pois);
                        }, 10000);
                    } else {
                        this.$ngBootbox.alert("数据库无法给出轨迹点，弹窗关闭退出").then( ()=> {
                            this.goback();
                            return;
                        })
                    }
                });
            }


        }

        judgealltime=()=> {
            if ( this.startTime == null || this.startTime == undefined) {
                this.$ngBootbox.alert("车辆还没有开始行驶，无法给出轨迹，弹窗关闭退出").then( ()=> {
                    return;
                })
            } else if (this.$scope.realArrivalTime === undefined || this.$scope.realArrivalTime === null || this.$scope.realArrivalTime === "") {
                this.start_end_all_points2(this.startTime, this.$scope.presentTime);
            } else {
                this.start_end_all_points(this.startTime, this.$scope.realArrivalTime);
            }
        }


        goback = ()=> {
            window.history.back();
        }
       
    

}

angular.module('tms').controller('ICarStrack',["$scope", "locationService", "orderService" ,"trackService","$location","$ngBootbox","$timeout" ,'routeService','$state',ICarStrack])